package cn.tedu._06springaop.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Aspect
@Component
public class LogAspect {

    @Pointcut("execution(public int cn.tedu._06springaop.aop.CalculatorImpl.*(..))")
    public void pointCut() {
    }

/*
    @Before("pointCut()")
    public void beforeMethod(JoinPoint joinPoint) {
        String name = joinPoint.getSignature().getName();
        String args = Arrays.toString(joinPoint.getArgs());
        System.out.println("[前置通知]" + name + "方法开始，参数为：" + args);
    }

    @After("pointCut()")
    public void afterMethod(JoinPoint joinPoint) {
        String name = joinPoint.getSignature().getName();
        System.out.println("[后置通知]" + name + "方法结束");
    }

    @AfterReturning(value = "pointCut()", returning = "result")
    public void afterReturningMethod(JoinPoint joinPoint, int result) {
        String name = joinPoint.getSignature().getName();
        System.out.println("[正常返回通知]" + name + "方法正常结束，返回值为" + result);
    }

    @AfterThrowing(value = "pointCut()", throwing = "ex")
    public void afterReturningMethod(JoinPoint joinPoint, Throwable ex) {
        String name = joinPoint.getSignature().getName();
        System.out.println("[异常通知]" + name + "方法抛出异常，异常信息为：" + ex.getMessage());
    }
*/

    @Around(value = "pointCut()")
    public Object aroundMethod(ProceedingJoinPoint joinPoint) {
        Object result = null;
        try {
            System.out.println("[环绕通知]前置通知");
            result = joinPoint.proceed();
            System.out.println("[环绕通知]返回通知");
        } catch (Throwable e) {
            System.out.println("[环绕通知]异常通知");
            throw new RuntimeException(e);
        }finally {
            System.out.println("[环绕通知]后置通知");
        }
        return result;
    }
}
